<template>
  <div class="hosts-container">
    <div class="header-section">
      <h1 class="page-title glow-text">主机管理</h1>
      <div class="header-actions">
        <el-button type="primary" @click="showAddDialog" class="tech-button">
          <i class="fa fa-plus"></i> 添加主机
        </el-button>
        <el-input
          v-model="searchText"
          placeholder="搜索主机名或IP地址..."
          clearable
          class="search-input"
          style="width: 300px; margin-left: 20px;"
        >
          <template #prefix>
            <i class="fa fa-search"></i>
          </template>
        </el-input>
      </div>
    </div>

    <div class="table-container tech-border">
      <el-table
        :data="filteredHosts"
        style="width: 100%"
        v-loading="loading"
        class="tech-table"
      >
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="hostname" label="主机名" min-width="150" />
        <el-table-column prop="public_ip" label="公网IP" min-width="130" />
        <el-table-column prop="private_ip" label="内网IP" min-width="130" />
        <el-table-column prop="port" label="端口" width="80" />
        <el-table-column prop="username" label="用户名" min-width="100" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeColor(scope.row.type)" size="small">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'online' ? 'success' : 'danger'" size="small">
              {{ scope.row.status === 'online' ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="connectHost(scope.row)">
              <i class="fa fa-terminal"></i> 连接
            </el-button>
            <el-button size="small" type="warning" @click="editHost(scope.row)">
              <i class="fa fa-edit"></i> 编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteHost(scope.row)">
              <i class="fa fa-trash"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑主机对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑主机' : '添加主机'"
      width="600px"
      class="tech-dialog"
    >
      <el-form :model="hostForm" :rules="hostRules" ref="hostFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="主机名" prop="hostname">
              <el-input v-model="hostForm.hostname" placeholder="请输入主机名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主机类型" prop="type">
              <el-select v-model="hostForm.type" placeholder="请选择主机类型" style="width: 100%">
                <el-option label="Web服务器" value="web" />
                <el-option label="数据库服务器" value="db" />
                <el-option label="应用服务器" value="app" />
                <el-option label="缓存服务器" value="cache" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公网IP" prop="public_ip">
              <el-input v-model="hostForm.public_ip" placeholder="请输入公网IP地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内网IP" prop="private_ip">
              <el-input v-model="hostForm.private_ip" placeholder="请输入内网IP地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="端口" prop="port">
              <el-input-number v-model="hostForm.port" :min="1" :max="65535" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="hostForm.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="认证方式" prop="auth_type">
          <el-radio-group v-model="hostForm.auth_type">
            <el-radio label="password">密码认证</el-radio>
            <el-radio label="key">密钥认证</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="hostForm.auth_type === 'password'" label="密码" prop="password">
          <el-input v-model="hostForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>

        <el-form-item v-if="hostForm.auth_type === 'key'" label="私钥" prop="private_key">
          <el-input v-model="hostForm.private_key" type="textarea" :rows="4" placeholder="请输入私钥内容" />
        </el-form-item>

        <el-form-item v-if="hostForm.auth_type === 'key'" label="私钥密码" prop="passphrase">
          <el-input v-model="hostForm.passphrase" type="password" placeholder="私钥密码（可选）" show-password />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="hostForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const store = useAppStore()

const loading = ref(false)
const searchText = ref('')
const hosts = ref([])

const filteredHosts = computed(() => {
  if (!searchText.value) return hosts.value
  return hosts.value.filter(host => 
    host.hostname.toLowerCase().includes(searchText.value.toLowerCase()) ||
    host.ip.includes(searchText.value)
  )
})

const addHost = () => {
  ElMessage.info('添加主机功能')
}

const editHost = (host: any) => {
  ElMessage.info(`编辑主机: ${host.hostname}`)
}

const deleteHost = (host: any) => {
  ElMessage.info(`删除主机: ${host.hostname}`)
}

const connectHost = async (host: any) => {
  try {
    // 请求SSH访问令牌
    const response = await axios.post('/api/ssh/request-access/', {
      host_id: host.id
    })

    if (response.data.success) {
      // 使用访问令牌跳转到SSH页面
      router.push(`/ssh/${host.id}?token=${response.data.access_token}`)
    } else {
      ElMessage.error(response.data.message || '无权访问此主机')
    }
  } catch (error) {
    console.error('请求SSH访问失败:', error)
    ElMessage.error('请求SSH访问失败，请检查权限')
  }
}

const fetchHosts = async () => {
  loading.value = true
  try {
    const response = await store.getHosts()
    hosts.value = response || []
  } catch (error) {
    console.error('获取主机列表失败:', error)
    ElMessage.error('获取主机列表失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchHosts()
})
</script>

<style lang="scss" scoped>
.hosts-container {
  padding: 20px;
}

h1 {
  color: #00eaff;
  margin-bottom: 20px;
  text-shadow: 0 0 10px rgba(0, 234, 255, 0.5);
}
</style>
